package com.qfedu.springmvc02.interceptor;

import com.qfedu.springmvc02.entity.User;

import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author zed
 * @date 2022/5/5 11:04
 * 自定义拦截器
 */
public class MyInterceptor implements HandlerInterceptor {

    // preHandle是在处理器Handler执行之前执行的 返回true就是让请求继续执行，false:后续拦截器和处理器不执行了直接返回
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // System.out.println("preHandle 执行...");
        // 登录权限验证的拦截
        // 从session中取出来登录的用户，判断用户是否登录过，然后决定是进行拦截或者放行
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(Objects.isNull(user)){
            // 说明没有登录，拦截，返回到登录页面
            request.setAttribute("error","用户名或密码错误");
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }
        // 如果登录过，就放行
        return true;
    }

}
